package likou;

import java.util.*;

/**
 * @author: Tangxz
 * @email: 1171702529@qq.com
 * @cate: 2021/01/18 10:45
 */
public class _721 {
    public static void main(String[] args) {
        List<List<String>> accounts = new ArrayList<>();
        accounts.add(new ArrayList<String>(Arrays.asList("John", "johnsmith@mail.com", "john00@mail.com")));
        accounts.add(new ArrayList<String>(Arrays.asList("John", "johnnybravo@mail.com")));
        accounts.add(new ArrayList<String>(Arrays.asList("John", "johnsmith@mail.com", "john_newyork@mail.com")));
        accounts.add(new ArrayList<String>(Arrays.asList("Mary", "mary@mail.com")));
        for (List list:accounts){
            System.out.println(Arrays.toString(list.toArray()));
        }
        System.out.println();
        accounts = accountsMerge(accounts);
        accounts.add(new ArrayList<String>(Arrays.asList("Mary", "mary@mail.com")));
        for (List list:accounts){
            System.out.println(Arrays.toString(list.toArray()));
        }
    }
    static class MyMap{
        String name;
        Set<String> emails;
        MyMap(){
            emails = new HashSet<>();
        }
        void emailsSet(List<String> nowEmails){
            emails.addAll(nowEmails);
        }
    }
    public static List<List<String>> accountsMerge(List<List<String>> accounts) {
        List<MyMap> daan = new ArrayList<>();
        for(List<String> list:accounts){
            boolean p = false;//是否是同一个人
            for(MyMap myMap:daan){
                if(list.get(0).equals(myMap.name)){
                    for(String str:list){
                        if(myMap.emails.contains(str)){
                            p=true;
                            break;
                        }
                    }
                }
                if(p){
                    list.remove(0);
                    myMap.emailsSet(list);
                    break;
                }
            }
            if(!p){
                MyMap nowMap = new MyMap();
                nowMap.name = list.get(0);
                list.remove(0);
                nowMap.emailsSet(list);
                daan.add(nowMap);
            }
        }
        List<List<String>> res = new ArrayList<>();
        for(MyMap myMap:daan){
            List<String> now = new ArrayList<>();
            now.add(myMap.name);
            now.addAll(myMap.emails);
            res.add(now);
        }
        return res;
    }
}
